package com.hxkj.mq.receiver;


import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.client.service.UniversalServiceClient;
import com.hxkj.client.service.taglib.*;
import com.hxkj.domain.Constant.CmsConstants;
import com.hxkj.domain.enums.TagsExceptionEnum;
import com.hxkj.domain.po.*;
import com.hxkj.mq.config.MQConstant;
import com.hxkj.utils.HanyuPinyinHelper;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static com.hxkj.domain.Constant.CmsConstants.*;

@Component
@Slf4j
public class MessageHandle {

    @Autowired
    private AnalyzeArticleService analyzeArticleService;
    @Autowired
    private AnalyzeChannelService analyzeChannelService;
    @Autowired
    private AnalyzeColumnService analyzeColumnService;
    @Autowired
    private AnalyzeLeafletService analyzeLeafletService;

    @Autowired
    private AnalyzeTagsService analyzeTagsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UniversalServiceClient universalServiceClient;
    @Autowired
    private ArticleServiceClient articleServiceClient;

    private static final String UNIVERA = "UNIVERAL_SITE";

    @RabbitHandler
    @RabbitListener(queues = MQConstant.ARTICLE_QUEUE, containerFactory = "rabbitListenerContainerFactory")
    public void analyzeArticle(Article article) {
        try {
            FreeMarker freeMarker = new FreeMarker();
            freeMarker.setArticleId(article.getArticleId());
            freeMarker.setTempletId(article.getTempletId());
            freeMarker.setWapTempletId(article.getWapTempletId());
            freeMarker.setChannelId(article.getArticleId().toString());
            freeMarker.setColumnId(article.getColumnId());
            freeMarker.setStatus(ARTICLEDETAIL);
            freeMarker.setSiteId(article.getSiteId());
            freeMarker.setAliasName("article");
            freeMarker.setTime(article.getCreateTime());
            analyzeArticleService.analyzeArticle(freeMarker);
        } catch (Exception e) {
            log.error("解析文章出错" , e);
        }
    }

    @RabbitHandler
    @RabbitListener(queues = MQConstant.CHANNEL_QUEUE, containerFactory = "rabbitListenerContainerFactory")
    public void analyzeChannel(Channel channel) {
        try {
            log.debug("执行生成频道 ChannelId: " + channel.getChannelId());
            FreeMarker freeMarker = new FreeMarker();
            freeMarker.setTempletId(channel.getTempletId());
            freeMarker.setWapTempletId(channel.getmTempletId());
            freeMarker.setAliasName(channel.getTempletName());
            freeMarker.setChannelId(channel.getChannelId().toString());
            freeMarker.setSiteId(channel.getSiteId());
            freeMarker.setStatus(CHANNEL);
            freeMarker.setTime(channel.getCreateTime());
            analyzeChannelService.analyzeChannel(freeMarker);
        } catch (Exception e) {
            log.error("解析频道出错", e);
        }
    }

    @RabbitHandler
    @RabbitListener(queues = MQConstant.COLUMN_QUEUE, containerFactory = "rabbitListenerContainerFactory")
    public void analyzeColumn(Column column) {
        try {
            String columnNamme = HanyuPinyinHelper.getFirstLettersLo(column.getColumnName());//将分类名称转为首字母拼写别名
            FreeMarker freeMarker = new FreeMarker();
            freeMarker.setTempletId(column.getTempId());
            freeMarker.setWapTempletId(column.getmListTempletId());
            freeMarker.setAliasName(columnNamme);
            freeMarker.setColumnId(column.getColumnId());
            freeMarker.setSiteId(column.getSiteId());
            freeMarker.setStatus(COLUMNLIST);
            freeMarker.setChannelId("-1");
            freeMarker.setPageNum(column.getCount());//分页当前页数
            freeMarker.setTime(column.getCreateTime());
            analyzeColumnService.analyzeColumn(freeMarker);
        } catch (Exception e) {
            log.error("生成分类出错", e);
        }
    }

    @RabbitHandler
    @RabbitListener(queues = MQConstant.LEAFLET_QUEUE, containerFactory = "rabbitListenerContainerFactory")
    public void analyzeLeaflet(Leaflet leaflet){
        try {
            FreeMarker freeMarker = new FreeMarker();
            freeMarker.setSiteId(leaflet.getSiteId());
            freeMarker.setChannelId("0");
            freeMarker.setTempletId(leaflet.getTempletId());
            freeMarker.setWapTempletId(leaflet.getmTempletId());
            freeMarker.setAliasName("leaflet");
            freeMarker.setLeafletId(leaflet.getLeafletId());
            freeMarker.setStatus(LEAFLET);
            freeMarker.setTime(leaflet.getCreateTime());
            analyzeLeafletService.analyzeLeaflet(freeMarker);
            log.info("执行生成单页 leafletId: " + leaflet.getLeafletId());
        } catch (Exception e) {
            log.error("解析单页出错", e);
        }
    }


    @RabbitHandler
    @RabbitListener(queues = MQConstant.TAG_INFO_QUEUE, containerFactory = "rabbitListenerContainerFactory")
    public void analyzeTags(Tags tags) {
        try {
            SiteUniversal siteUniversal = getSiteUniversal(tags.getSiteId());
            if (siteUniversal == null && siteUniversal.getTagsTempletId() == null) {
                log.info("单页失败{}", TagsExceptionEnum.TAGS_TEMPLET_NOT_EXIST);
            }
            analyzeTagPath(tags, siteUniversal);
        } catch (Exception e) {
            log.error("解析标签出错" , e);
        }
    }


    protected SiteUniversal getSiteUniversal(Long siteId) throws Exception {
        SiteUniversal siteUniversal = (SiteUniversal) redisTemplate.opsForValue().get(UNIVERA + siteId);
        if (siteUniversal != null) return siteUniversal;
        SiteUniversal siteUniversalData = new SiteUniversal();
        siteUniversalData.setSiteId(siteId);
        return universalServiceClient.get(siteUniversalData).getData();
    }

    protected void analyzeTagPath(Tags tags, SiteUniversal siteUniversal) throws Exception {
        PageTo pageTo = getPageToByTags(tags, new PageTo());//获取当前tag下的文章列表的分页数据
        FreeMarker freeMarker = new FreeMarker();
        int i = 1;
        do {
            //生成tag详情页
            freeMarker.setTempletId(siteUniversal.getTagsTempletId());
            freeMarker.setWapTempletId(siteUniversal.getmTempletId());
            freeMarker.setAliasName("tag");
            freeMarker.setTagsId(tags.getTagsId());
            freeMarker.setStatus(TAGSDEATIL);//5标识tags详情
            freeMarker.setChannelId("-1");
            freeMarker.setPageNum(i);//分页当前页数
            freeMarker.setSiteId(tags.getSiteId());
            freeMarker.setTime(tags.getCreateTime());
            analyzeTagsService.analyzeTagArticle(freeMarker);
            i++;
        } while (i <= pageTo.getPages());
    }


    private PageTo getPageToByTags(Tags tags, PageTo pageParam) throws Exception {
        pageParam.setPageNum(1);
        pageParam.setPageSize(10);

        Article article = new Article();
        article.setTagsId(tags.getTagsId());
        article.setSiteId(tags.getSiteId());
        article.setAuditType(0);
        article.setDelTag(0);

        ParameterDataStruct<Article> parameterDataStruct = new ParameterDataStruct<>();
        parameterDataStruct.setData(article);
        parameterDataStruct.setPageTo(pageParam);
        ResultPageStruct<Article> pageInfo = articleServiceClient.getArticleList(parameterDataStruct);//获取文章列表及其分页数据
        return pageInfo.getPageInfo();
    }


    /**
     * 进度+1
     * @param type
     * @param object
     */
    protected void progress(Long type, Object object) {
        if (type == CmsConstants.CHANNEL) {
            Channel channel = (Channel) object;
            String socketKey = channel.getSocketKey();
            if (StringUtils.isNotBlank(socketKey)) {
                redisTemplate.opsForValue().increment(socketKey, 1);
            }
        } else if (type == CmsConstants.ARTICLEDETAIL) {
            Article article = (Article) object;
            String socketKey = article.getSocketKey();
            if (StringUtils.isNotBlank(socketKey)) {
                redisTemplate.opsForValue().increment(socketKey, 1);
            }
        } else if (type == CmsConstants.COLUMNLIST) {
            Column column = (Column) object;
            String socketKey = column.getSocketKey();
            if (StringUtils.isNotBlank(socketKey)) {
                redisTemplate.opsForValue().increment(socketKey, 1);
            }
        } else if (type == CmsConstants.LEAFLET) {
            Leaflet leaflet = (Leaflet) object;
            String socketKey = leaflet.getSocketKey();
            if (StringUtils.isNotBlank(socketKey)) {
                redisTemplate.opsForValue().increment(socketKey, 1);
            }
        } else if (type == CmsConstants.TAGSDEATIL) {
            Tags tags = (Tags) object;
            String socketKey = tags.getSocketKey();
            if (StringUtils.isNotBlank(socketKey)) {
                redisTemplate.opsForValue().increment(socketKey, 1);
            }
        }
    }
}
